package com.avic.rong.search.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.bean.product.GoodBean;
import com.avic.rong.bean.product.SearchGroupBean;
import com.avic.rong.goodsSort.adapter.secondListAdapter.GoodsSortBzShowSxRvAdapter;
import com.avic.rong.goodsSort.adapter.secondListAdapter.StandardItemAdapter;
import com.avic.rong.goodsSort.api.StandardSearchApi;
import com.avic.rong.goodsSort.bean.showRvBean.GoodsSortSearchAllBzBean;
import com.avic.rong.goodsSort.bean.showRvBean.GoodsSortSearchAllBzSxBean;
import com.avic.rong.search.MessageEvent;
import com.avic.rong.search.activity.SearchResaultActivity;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchVpBzRvAdapter;
import com.avic.rong.userOrder.api.AddCarApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchStandardFragment extends Fragment implements SearchVpBzRvAdapter.SearchHomePageBzListener, GoodsSortBzShowSxRvAdapter.GoodsBzSxRvListener, OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.recycler_list)
    RecyclerView recycler_list;


    @BindView(R.id.search_vp_bz_tv)
    TextView searchVpBzTv;

    @BindView(R.id.beijing_image)
    ImageView beijing_image;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;


    private List<GoodBean> goodBeanList = new ArrayList<>();


    private Context mContext;


    private StandardItemAdapter standardItemAdapter;

    private SearchVpBzRvAdapter adapter;
    private List<GoodsSortSearchAllBzBean.DataBean> list = new ArrayList<>();
    private List<GoodsSortSearchAllBzSxBean.DataBean> bzShaiXuanBeanList = new ArrayList<>();
    private GoodsSortBzShowSxRvAdapter showSxRvAdapter;
    String currentText = "GJB";
    private static int pageNo = 1;
    private StandardSearchApi standardSearchApi;

    public SearchStandardFragment() {
        // Required empty public constructor
    }


    public SearchStandardFragment getInstance(Context context) {
        SearchStandardFragment standardFragment = new SearchStandardFragment();
        standardFragment.mContext = context;
        return standardFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_standard, container, false);


//        initBzData(currentText, pageNo);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        recycler_list.setLayoutManager(new LinearLayoutManager(getActivity()));
//        adapter = new SearchVpBzRvAdapter(getContext(), list);
//        adapter.setListener(SearchStandardFragment.this);
//        searchBiaoZhunRv.setAdapter(adapter);

        standardItemAdapter = new StandardItemAdapter(mContext, 1);
        recycler_list.setAdapter(standardItemAdapter);

        standardSearchApi = new StandardSearchApi((BaseActivity) mContext, searchAllListener);
        standardSearchApi.setTypes(1);
        standardSearchApi.setKeyword("gjb");
        HttpManager.getInstance().doHttpDeal(standardSearchApi);

        return view;
    }


    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> searchAllListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            loading_layout.setStatus(LoadingLayout.SUCCESS);

//            CircleProgressDialog.closeDialog();
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                ToastTools.showToast(mContext, subjects.getMsg());
                Logger.e("cjx", "biaozhun数据：" + subjects.getMsg());
                return;
            }
            List<SearchGroupBean> beans = (List<SearchGroupBean>) subjects.getData();


//            StandardItemAdapter standardItemAdapter = new StandardItemAdapter(mContext, 1);
            goodBeanList.addAll(beans.get(0).getData());

            standardItemAdapter.setBeanList(goodBeanList);
//            standardItemAdapter.setBeanList(goodBeanList);


        }


        @Override
        public void onError(final Throwable e) {
            CircleProgressDialog.closeDialog();
//            if (isRefresh) {
//                refreshLayout.finishRefresh();
//            } else {
//                refreshLayout.finishLoadMore();
//            }
//            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
//                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
//            } else {
//                loading_layout.setStatus(LoadingLayout.ERROR);
//            }
            Logger.e("cjx", "bz拿到数据" + e.getMessage());
        }
    };


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        list.clear();
        pageNo = 1;
//        initBzData(currentText, pageNo);
//        searchFragmentBzSmartRefreshLayout.finishRefresh(1000);
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        ++pageNo;
//        initBzData(currentText, pageNo);
//        searchFragmentBzSmartRefreshLayout.finishLoadMore(1000);
    }




    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void cha(MessageEvent msg) {
        if (msg != null) {
            if (msg.getType().equals("bzSure")) {
                bzShaiXuanBeanList.clear();
                String attrPro = msg.getMessage();
                initBzSureData(attrPro);
            } else {
                return;
            }
        }
    }

    private void initBzSureData(String attrPro) {
//        GoodsSortSearchAllBzSXApi searchAllSxApi = new GoodsSortSearchAllBzSXApi((SearchResaultActivity) getActivity(), searchAllTsSxListener, 1, attrPro);
//        searchAllSxApi.setCache(false);
//        HttpManager.getInstance().doHttpDeal(searchAllSxApi);
    }





    @Override
    public void searchHomePageBiaoZhunBzAddCar(String skuStr) {
        AddCar(skuStr);
    }

    //添加购物车
    private void AddCar(String skuStr) {
        Log.e("cjx", "skuStr:" + skuStr);

        Map<String, String> map = new HashMap<>();
        map.put("skuStr", skuStr);
        map.put("orderType", 4 + "");
//            是否再次购买（0/1）
        map.put("buyAgain", 0 + "");
        if (SharedPreferencesUtil.isLogin()) {
            map.put("token", SharedPreferencesUtil.getLoginToken());
        }
//        map.put("deviceId", DeviceUtils.getIMEString(context));
        final AddCarApi addCarApi = new AddCarApi((SearchResaultActivity) getActivity(), simpleOnNextListenerAddCar);
        addCarApi.setCache(false);
        addCarApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(addCarApi);

    }

    //添加购物车
    HttpOnNextListener simpleOnNextListenerAddCar = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                return;
            }
//            ToastTools.showToast(context, "添加成功");
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    @Override
    public void addBzSxCar(String skuStr, GoodsSortBzShowSxRvAdapter.GoodsSortBzShowRvViewHolder holder) {
        AddCar(skuStr);
    }
}
